import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_math_fork/flutter_math.dart';
import 'package:markdown/markdown.dart' as md;

/// 块级LaTeX公式构建器
/// 用于将块级LaTeX公式渲染为Flutter小部件
class LatexBuilder extends MarkdownElementBuilder {
  final TextStyle? style;
  final double textScaleFactor;

  LatexBuilder({this.style, this.textScaleFactor = 1.0});

  @override
  Widget? visitElementAfter(md.Element element, TextStyle? preferredStyle) {
    final latex = element.textContent;
    if (latex.isEmpty) return const SizedBox();

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Center(
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Math.tex(
            latex,
            textStyle: style ?? preferredStyle,
            mathStyle: MathStyle.display,
            textScaleFactor: textScaleFactor,
          ),
        ),
      ),
    );
  }
}

/// 行内LaTeX公式构建器
/// 用于将行内LaTeX公式渲染为Flutter小部件
class InlineLatexBuilder extends MarkdownElementBuilder {
  final TextStyle? style;
  final double textScaleFactor;

  InlineLatexBuilder({this.style, this.textScaleFactor = 1.0});

  @override
  Widget? visitElementAfter(md.Element element, TextStyle? preferredStyle) {
    final latex = element.textContent;
    if (latex.isEmpty) return const SizedBox();

    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Math.tex(
        latex,
        textStyle: style ?? preferredStyle,
        mathStyle: MathStyle.text,
        textScaleFactor: textScaleFactor,
      ),
    );
  }
}